package com.itheima.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingMapper;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfoVo;
import com.itheima.pojo.OrderSetting;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderDao orderDao;
    @Autowired
    MemberDao memberDao;
    @Autowired
    OrderSettingMapper orderSettingMapper;


    @Override
    public synchronized   Result submit(OrderInfoVo orderInfoVo) {
        Date orderDate = orderInfoVo.getOrderDate();
        String telephone = orderInfoVo.getTelephone();
        Integer sex = orderInfoVo.getSex();
        String name = orderInfoVo.getName();
        String idCard = orderInfoVo.getIdCard();
        Integer setmealId = orderInfoVo.getSetmealId();
        String orderType = orderInfoVo.getOrderType();

        //1、根据预约日期查询是否存在预约设置
       OrderSetting orderSetting =  orderSettingMapper.findByDate(orderDate);
       //线程1 200 199 0
       //线程2 200 199 0
       //线程3 200 199 0
       //线程4 200 199 0
       if(null == orderSetting){
           return Result.error("没有档期");
       }
        //2、查看是否约满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(number <= reservations){
            return Result.error("预约已满");
        }
        //3、根据手机号码查询是否是我们的会员
        Member member = memberDao.findByTelephone(telephone);
        //4、如果不是就自动注册
        if(null == member){
            member = new Member();//一定要new
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            member.setSex(String.valueOf(sex));
            member.setName(name);
            member.setIdCard(idCard);
            memberDao.add(member);//一定要返回主键
        }
        Integer memberId = member.getId();
        //5、根据会员id，套餐id，预约日期是否已经存在预约信息
        Order query = new Order();
        query.setSetmealId(setmealId);
        query.setOrderDate(orderDate);
        query.setMemberId(memberId);
        List<Order> orders = orderDao.findByCondition(query);
        if(CollectionUtil.isNotEmpty(orders)){
            return Result.error("不要重复预约");
        }
        //6、直接下单
        Order order = new Order();
        order.setMemberId(memberId);
        order.setSetmealId(setmealId);
        order.setOrderDate(orderDate);
        order.setOrderType(orderType);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        orderDao.add(order);

        //7、已预约人数 + 1

        orderSetting.setReservations(orderSetting.getReservations() + 1);
        int i = orderSettingMapper.editReservations(orderSetting); //cas
//        if(0 == i){
//            throw new RuntimeException("更新失败");
//        }

        return Result.success("",order);//页面需要使用订单id
    }

    @Override
    public Map findById(Integer id) {
        return orderDao.findById4Detail(id);
    }

    @Override
    public Result phoneSetOrderSetting(Map map) {
        try {
            String name = (String) map.get("name");
            String phoneNumber = (String)map.get("phoneNumber");
            String idCard = (String)map.get("idCard");
            String sex = (String)map.get("sex");
            List<Integer> checkgroupIds = (List<Integer>) map.get("checkgroupIds");
            String date = (String) map.get("orderDate");
//            date = date.replace("Z", " UTC");
           SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//            format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            Date orderDate = format.parse(date);

            //根据预约日期查询是否满
            OrderSetting orderSetting =  orderSettingMapper.findByDate(orderDate);
            if(null == orderSetting){
                return Result.error("没有档期");
            }
            int number = orderSetting.getNumber();//可预约人数
            int reservations = orderSetting.getReservations();//已预约人数
            if(number <= reservations){
                return Result.error("预约已满");
            }
            //根据用户手机判断是否为会员不是帮忙注册
            Member member = memberDao.findByTelephone(phoneNumber);
            if (member == null) {
                member = new Member();//一定要new
                member.setPhoneNumber(phoneNumber);
                member.setRegTime(new Date());
                member.setSex(String.valueOf(sex));
                member.setName(name);
                member.setIdCard(idCard);
                memberDao.add(member);//一定要返回主键
            }
            Integer memberId = member.getId();
            //根据会员id，套餐id，预约日期是否已经存在预约信息
            Order query = new Order();
            query.setSetmealId(checkgroupIds.get(0));
            query.setOrderDate(new Date());
            query.setMemberId(memberId);
            List<Order> orders = orderDao.findByCondition(query);
            if(CollectionUtil.isNotEmpty(orders)){
                return Result.error("不要重复预约");
            }
            //6、直接下单
            Order order = new Order();
            order.setMemberId(memberId);
            order.setSetmealId(checkgroupIds.get(0));
            order.setOrderDate(orderDate);
            order.setOrderType(Order.ORDERTYPE_TELEPHONE);
            order.setOrderStatus(Order.ORDERSTATUS_NO);
            orderDao.add(order);
            orderSetting.setReservations(orderSetting.getReservations() + 1);
            int i = orderSettingMapper.editReservations(orderSetting);
            if (i == 0) {
                throw new RuntimeException("更新失败");
            }
            return Result.success("");
        } catch (ParseException e) {
            e.printStackTrace();
            return Result.error("");
        }

    }
}
